package com.hc.controller;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.constant.GlobalConstant;
import com.hc.domain.User;
import com.hc.dto.UserLoginDto;
import com.hc.jwt.JwtUtil;
import com.hc.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "userLoginDto", value = "用户登录信息", required = true, dataType = "UserLoginDto"),
    })
    @PostMapping(value = "/login")
    public Result userLogin(@RequestBody @Valid UserLoginDto userLoginDto,
                            HttpServletResponse response) {
        User user = userService.getUserByUsername(userLoginDto.getUsername());
        // 用户不存在
        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }

        // 用户被锁定
        if (GlobalConstant.User.USER_STATUS_LOCKED.equals(user.getStatus())) {
            throw new LockedAccountException("该用户已被锁定，暂时无法登录！");
        }

        if (!user.getPassword().equals(JwtUtil.saltPassword(userLoginDto.getPassword(), user.getSalt()))) {
            throw new IncorrectCredentialsException("密码不匹配，请检查后重新输入！");
        }

        // 若登录成功，签发 JWT token
        String jwtToken = JwtUtil.createToken(userLoginDto.getUsername(), GlobalConstant.Jwt.SECRET);
        // 将签发的 JWT token 设置到 HttpServletResponse 的 Header 中
        System.out.println("jwtToken:  " + jwtToken);
        response.setHeader(GlobalConstant.Jwt.AUTH_HEADER, jwtToken);
        response.setHeader("Access-control-Expose-Headers", "x-auth");

        return ResultUtil.success("登录成功", user);
    }

    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        //在这里执行退出系统前需要清空的数据
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        System.out.println("退出登录成功");
        return ResultUtil.success("退出登录");
    }

}
